//
//  ShopOfSelectVC.m
//  PetAPP
//
//  Created by apple on 16/2/21.
//  Copyright © 2016年 Yuming. All rights reserved.
//

#import "ShopOfSelectVC.h"
#import "ModelOfShop.h"
#import "NetworkingHandle.h"
#import <MJRefresh.h>
#import "ModelOfShopForDetail.h"
#import "CellOfShopForSelectDeatil.h"


@interface ShopOfSelectVC () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) UISegmentedControl *sg;

@property (nonatomic, retain) UILabel *labelOfTime;

@property (nonatomic, assign) BOOL flagForMetthod;

@property (nonatomic, assign) NSTimeInterval endTime;

@property (nonatomic, retain) UICollectionView *collection;

@property (nonatomic, retain) NSMutableArray *dataArr;

@end

@implementation ShopOfSelectVC

- (void)dealloc {

    [_sg release];
    [_labelOfTime release];
    [_collection release];
    [super dealloc];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self createHeaderView];
    [self handleData];
    [self createSubViews];
    [self handleRefresh];
}

- (void)handleRefresh {
    
    self.collection.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self handleData];
    }];

}


- (void)handleData {
    
    NSString *method = nil;
    if (self.flagForMetthod == NO) {
        method = @"&sort_sold=DESC";
    }else {
        method = @"DESC&sort_sold=";
    }
    NSString *body = [NSString stringWithFormat:@"page=1&pageSize=10&sort_price=%@&topic_id=%@", method, self.topicId];
    
    [NetworkingHandle handleWorkData:@"http://ts.leepet.com/plugins/API.v1.0/?&a=goods&m=goodsList" AndBody:body value:@{@"Content-Type" : @"application/x-www-form-urlencoded"} handleBlock:^(id result) {
        
        NSDictionary *tempDic = [result objectForKey:@"data"];
        
        
        /** 用结束时间减去当前时间，剩下多少天 */
        NSDate *endDate = [NSDate dateWithTimeIntervalSince1970:[[[tempDic objectForKey:@"timeinfo"] objectForKey:@"end_time"] intValue]];
        NSDate *now = [NSDate date];
        self.endTime = [endDate timeIntervalSinceDate:now];
        
        
        [self handleTime];
        
        /** 获取宠物商品列表 */
        self.dataArr = [NSMutableArray array];
        
        NSArray *tempArr = [tempDic objectForKey:@"info"];
        
        for (NSDictionary *dic in tempArr) {
            
            ModelOfShopForDetail *model = [[ModelOfShopForDetail alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataArr addObject:model];
            [model release];
        }
        
        [self.collection reloadData];
        [self.collection.mj_header endRefreshing];
    }];
    
    
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    CellOfShopForSelectDeatil *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfCell" forIndexPath:indexPath];
    
    ModelOfShopForDetail *model = [self.dataArr objectAtIndex:indexPath.item];
    
    [cell handleDataWithModel:model];
    cell.backgroundColor = [UIColor whiteColor];
    
    return cell;

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (void)createSubViews {

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    flowLayout.sectionInset = UIEdgeInsetsMake(15, 5, 40, 5);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumLineSpacing = 5;
    flowLayout.minimumInteritemSpacing = 5;
    
    flowLayout.itemSize = CGSizeMake((self.view.frame.size.width - 15) / 2, 200);
    
    
    
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 144, self.view.frame.size.width, self.view.frame.size.height - 144) collectionViewLayout:flowLayout];
    [self.view addSubview:_collection];
    [_collection release];
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    
    self.collection.backgroundColor = [UIColor colorWithRed:0.9625 green:0.9625 blue:0.9625 alpha:1.0];
    
    
    [self.collection registerClass:[CellOfShopForSelectDeatil class] forCellWithReuseIdentifier:@"poolOfCell"];


}

- (void)handleTime {
    
    self.labelOfTime.text = [NSString stringWithFormat:@"距结束%d天%d时%d分%d秒", (int)self.endTime / 60 / 60 / 24, (int)(self.endTime / 60.f / 60.f) % 24, (int)(self.endTime / 60.f) % 60, (int)self.endTime % 60];
    

}


- (void)createHeaderView {
    
    self.sg = [[UISegmentedControl alloc] initWithItems:@[@"销量", @"价格"]];
    self.sg.frame = CGRectMake(0, 64, self.view.frame.size.width, 40);
    [self.view addSubview:_sg];
    [_sg release];
    self.sg.selectedSegmentIndex = 0;
    
    self.sg.backgroundColor = [UIColor whiteColor];
    NSDictionary *selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName: [UIColor colorWithRed:0.2784 green:0.0 blue:0.0667 alpha:1.0]};
    [self.sg setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
    
    /** 设置字体非选中时颜色 */
    NSDictionary *unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:14],NSForegroundColorAttributeName: [UIColor colorWithRed:255/256.0 green:207/256.0 blue:87/256.0 alpha:1]};
    [self.sg setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    [self.sg setTintColor:[UIColor colorWithRed:255/256.0 green:207/256.0 blue:87/256.0 alpha:1]];
    
    [self.sg addTarget:self action:@selector(changeSegmentSelect:) forControlEvents:UIControlEventValueChanged];

    
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 104, self.view.frame.size.width, 40)];
    [self.view addSubview:view];
    [view release];
    view.backgroundColor = [UIColor colorWithRed:0.8756 green:0.8756 blue:0.8756 alpha:1.0];
    
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(55, 5, 30, 30)];
    [view addSubview:imageView];
    [imageView release];
    imageView.image = [UIImage imageNamed:@"daojishijian"];
    
    self.labelOfTime = [[UILabel alloc] initWithFrame:CGRectMake(90, 5, self.view.frame.size.width - 100, 30)];
    [view addSubview:_labelOfTime];
    [_labelOfTime release];
    self.labelOfTime.textAlignment = NSTextAlignmentLeft;
    self.labelOfTime.textColor = [UIColor colorWithRed:0.9529 green:0.8118 blue:0.1529 alpha:1.0];
    self.labelOfTime.font = [UIFont systemFontOfSize:20];
    
    
    
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFire) userInfo:nil repeats:YES];
    
}

- (void)changeSegmentSelect:(UISegmentedControl *)sg {

    if (sg.selectedSegmentIndex == 0) {
        self.flagForMetthod = NO;
        [self handleData];
    }else {
        self.flagForMetthod = YES;
        [self handleData];
    }

}

- (void)timeFire {
    self.endTime--;
    [self handleTime];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
